//------------------------------------------------------------------------------
//  <copyright file="LineSegment2D.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Geometry
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Text;
    using System.Threading.Tasks;

    using Microsoft.Robotics.Numerics;

    /// <summary>
    /// Class representing a 2-D line in point/vector notation.
    /// </summary>
    [DebuggerDisplay("<{EndpointA}, {EndpointB}>")]
    [DataContract]
    public class LineSegment2D : Line2D
    {
        /// <summary>
        /// maximum X point
        /// </summary>
        [DataMember]
        private double maxX;

        /// <summary>
        /// minimum X point
        /// </summary>
        [DataMember]
        private double minX;

        /// <summary>
        /// maximum Y point
        /// </summary>
        [DataMember]
        private double maxY;

        /// <summary>
        /// minimum Y point
        /// </summary>
        [DataMember]
        private double minY;

        /// <summary>
        /// Initializes a new instance of the <see cref="LineSegment2D"/> class.
        /// </summary>
        /// <param name="a">A point on the line.</param>
        /// <param name="b">Another point on the line.</param>
        public LineSegment2D(Point2D a, Point2D b)
            : base(a, b)
        {
            this.EndpointA = a;
            this.EndpointB = b;

            // cache the min and max X and Y values so we don't need
            // to determine this every time we compute intersections
            this.maxX = Math.Max(this.EndpointA.X, this.EndpointB.X);
            this.minX = Math.Min(this.EndpointA.X, this.EndpointB.X);

            this.maxY = Math.Max(this.EndpointA.Y, this.EndpointB.Y);
            this.minY = Math.Min(this.EndpointA.Y, this.EndpointB.Y);
        }

        /// <summary>
        /// Gets endpoint A
        /// </summary>
        [DataMember]
        public Point2D EndpointA { get; private set; }

        /// <summary>
        /// Gets endpoint B
        /// </summary>
        [DataMember]
        public Point2D EndpointB { get; private set; }

        /// <summary>
        /// Get the points of intersection with the line segment and a geometry element.
        /// Only returns locations where hulls intersect at a point, and does not consider
        /// other types of intersections or the area of overlap.
        /// </summary>
        /// <param name="e">A geometry element.</param>
        /// <returns>List of intersection points.</returns>
        public override List<Point2D> GetIntersectionPoints(GeometryElement2D e)
        {
            List<Point2D> points;
            if (!(e is LineSegment2D))
            {
                points = new List<Point2D>();
                List<Point2D> candidatePoints = base.GetIntersectionPoints(e);

                foreach (Point2D p in candidatePoints)
                {
                    if (this.IsBetween(p))
                    {
                        points.Add(p);
                    }
                }
            }
            else
            {
                // for intersections between two line segements, first treat as an intersection between two points
                // and then see if the intersection point (if any) is on both segments
                LineSegment2D lineSegment = e as LineSegment2D;

                points = base.GetIntersectionPoints(new Line2D(lineSegment.A, lineSegment.A + lineSegment.N));

                if (points.Count == 1)
                {
                    if (!(this.IsBetween(points[0]) && lineSegment.IsBetween(points[0])))
                    {
                        // just return an empty list if the point isn't on both segments
                        return new List<Point2D>();
                    }
                }
            }

            return points;
        }

        /// <summary>
        /// Get the distance from the line segment to a point
        /// </summary>
        /// <param name="point">A point.</param>
        /// <returns>Distance from the point.</returns>
        public override double DistanceFrom(Point2D point)
        {
            if (this.IsBetween(point + ((this.A - point) - (Vector2.Dot(this.A - point, this.N) * this.N))))
            {
                return base.DistanceFrom(point);
            }
            else
            {
                return Math.Min((point - this.EndpointA).Length(), (point - this.EndpointB).Length());
            }
        }

        /// <summary>
        /// Determines if the given point lies between the line segments endpoints.
        /// Assumes that the point lies on the line.
        /// </summary>
        /// <param name="point">A 2D point.</param>
        /// <returns>True if the point lies between segment endpoints.</returns>
        internal bool IsBetween(Point2D point)
        {
            if (point.X >= this.minX &&
                point.X <= this.maxX &&
                point.Y >= this.minY &&
                point.Y <= this.maxY)
            {
                return true;
            }

            return false;
        }
    }
}
